package listeners;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import server.Conf;

public class MainServerHighListener extends Thread {

	private static final int PORT_BEATER = 5190;
	private static final int PORT_INSTR = 5230;
	
	private static final String mainServerAddress = "localhost";
	private static final String backupServerAddress = "localhost";
	
	protected boolean active;
	
	protected ServerSocket serverSocket;
	
	private Conf conf;
	
	public MainServerHighListener(Conf conf) throws IOException{
		
		active = true;
		
		serverSocket = new ServerSocket(PORT_BEATER);
		serverSocket.setSoTimeout(1200);
		
		this.conf = conf;
	}
	
	public void run(){
		
		while(active){
		
			try {
				Socket beatSocket = serverSocket.accept();
				ObjectInputStream ois = new ObjectInputStream(beatSocket.getInputStream());
				Boolean serverAlive = (Boolean)ois.readObject();
				
				//Puerto Alta Prioridad Activo
				if(serverAlive){
					conf.setMainServerHighPortActive(true);
					if(conf.isMainServerLowPortActive()){
						if(!conf.isMainServerActive()){
							sendInstruction(backupServerAddress, "suspend");
							sendInstruction(mainServerAddress, "migrate");
							sendInstruction(backupServerAddress, "migrate");
						}
						conf.setMainServerActive(true);
					}
					//System.out.println("Servidor 1 - Puerto Alta activo " + conf.isMainServerHighPortActive());
				}
				
				beatSocket.close();
				
			} 
			catch(SocketTimeoutException e){
				conf.setMainServerHighPortActive(false);
				if(conf.isMainServerActive()){
					sendInstruction(backupServerAddress, "resume");
				}
				conf.setMainServerActive(false);
				//System.out.println("Servidor 1 - Puerto Alta inactivo " + conf.isMainServerHighPortActive());
			}
			catch (IOException e) {
				e.printStackTrace();
			} 
			catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			 
		}
         
	}
	
	public void sendInstruction(String serverAddress, String instruction){
		
		try{
			Socket socket = new Socket(serverAddress, PORT_INSTR);
			
			ObjectOutputStream outStream = new ObjectOutputStream(socket.getOutputStream());
			outStream.writeObject(instruction);
			
			socket.close();
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}
}
